package com.ustarlink.socketserver;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;



public class SocketServer {
	BufferedWriter writer = null;
	BufferedReader reader = null;

	public static void main(String[] args) {
		SocketServer socketServer = new SocketServer();
		socketServer.startServer();
		
	}
	
	public void startServer() {
		ServerSocket serverSocket = null;
		Socket socket = null;
		try {
			serverSocket = new ServerSocket(8989);
			System.out.println("Server Start...");
			while(true){
				socket = serverSocket.accept();
				manageConnection(socket);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			try {
				socket.close();
				serverSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	public void manageConnection(final Socket socket) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					System.out.println("client " + socket.hashCode() + " connected");
					reader = new BufferedReader(
							new InputStreamReader(socket.getInputStream()));
					writer = new BufferedWriter(
							new OutputStreamWriter(socket.getOutputStream()));
					
					String receivedMsg;
					while((receivedMsg = reader.readLine()) != null){
						System.out.println("server receviedMsg: " + receivedMsg);
						writer.write("server reply: " + receivedMsg + "\n");
						writer.flush();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}  finally {
					try {
						writer.close();
						reader.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
}
